<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: PHP@妖孽 <dino_ma@163.com>
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
 * 用户中心
 +------------------------------------------------------------------------------
 * @version   1.0
 * @since 2015-11-19
 +------------------------------------------------------------------------------
 */
namespace Home\Controller;
use Think\Controller;


class CustomerController extends HomeController {
	
    public function _initialize(){
        parent::_initialize();
        //非登录状态下不允许访问的页面
        $arr = array('order');
        if(in_array_case(ACTION_NAME, $arr)){
            if(!is_login()){
                $this->redirect('login');
            }
        }
    }

	/**
     * @todo 后台首页，即订单页面
     * @author mahuan <mahuan@hrbjjhh.com>
     */
	public function order(){
        $activity_id = -1;
        $p = (int)I('p');
        $p = ($p-1<0) ? 0 : $p - 1;
        $merchant_obj = D('Api/Merchant','Service');
        $order_list = $merchant_obj->getOrderList(UID, $activity_id, 0, $p);
        if(IS_AJAX){
            if(0 == $order_list["status"]){
                $data['status'] = 0;
                $data['info'] = $order_list['info'];
                $this->ajaxReturn($data);
            }
            $obj = D('Customer');
            $list = $obj->getMobileOrder($order_list);
            $data['status'] = 1;
            $data['info'] = '获取数据成功';
            $data['data'] = $list['data'];
            $this->ajaxReturn($data);
        }
        $this->assign('meta_title','我的订单');
        if(isMobile()){
            $this->display('Customer/mobile/order');
        }else{
            $page = '';
            if($order_list["status"] == 1){
                $page = new \Think\Page($order_list["data"]["count"], 10);
                $page->setConfig('prev','<<');
                $page->setConfig('next','>>');
                $page->setConfig('theme', '<span class="pages"> %FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%</span>');
                $page = $page->show();
            }
            $this->assign('_page', $page);
            $this->assign("order_list",$order_list);
            $this->display();
        }
	}

    /**
     * @todo 后台用户登录
     * @author mahuan <mahuan@hrbjjhh.com>
     */
    public function login(){
        if(IS_POST){
            $phone = trim(strip_tags(I('phone')));
            $code = (int)I('code');
            if(!preg_match('/^1[3-8][0-9]{9}$/', $phone)){
                $this->error('请输入有效的手机号码');
            }
            if($code == 0){
                $this->error('请输入验证码');
            }
            $session_code = session('sms_code');
            //验证码判断
            if($session_code == $code || $code == C('LOGIN_NO_CHECK')){
                //获取用户信息
                D('Customer')->autoLogin($phone); 
                if(session('login_return_url') == U('login','',true,true)){
                    $redirect_url = U('Index/index');
                }else{
                    $redirect_url = (session('login_return_url'))?session('login_return_url'):U('Index/index');
                }
                if(IS_AJAX){
                    $this->ajaxReturn(array('status'=>1,'url'=>$redirect_url));
                }
                if(IS_POST){
                    $this->success('登录成功～',$redirect_url);
                }
            }else{
                $this->error('验证码输入错误或失效');
            }
        }
	    session('login_return_url',$_SERVER['HTTP_REFERER']);
        if(is_login()){
            $this->redirect('Customer/order');
		}
	    $this->meta_title="会员登陆";
        $template = isMobile() ? 'Customer/mobile/login' : '';
        $this->display($template);
    }

    /**
     * @todo 退出登录
     * @author mahuan <mahuan@hrbjjhh.com>
     */
    public function logout(){
        if(is_login()){
            D('Customer')->autoLoginOut();
            session('[destroy]');
            $this->success('退出成功！', U('login'));
        }
        $this->redirect('login');
    }

    /**
     * @todo    获取验证码（登录）
     * @param   string      $login_name     手机号
     * @author mahuan <mahuan@hrbjjhh.com>
     */
    public function getSms(){
        $phone = trim(I('phone'));
        if(!preg_match('/^1[3-8][0-9]{9}$/', $phone)){
            $this->error('请输入有效的手机号码');
        }
        //每分钟只能发一次
        $session_begin_time = session("sms_begin_times");
        $session_code_begin_time = session("code_begin_time");
        $session_code = session('sms_code');
        //如果没有发送过，大于一分钟则可以发送
        if(empty($session_begin_time) || ((NOW_TIME - $session_begin_time) > 60)){
        	session("sms_begin_times",NOW_TIME);
        	//如果没有生成过验证码，或验证码时间超过10分钟，则重新生成
        	if(empty($session_code_begin_time) || (NOW_TIME - $session_code_begin_time > 600)){
        		session("code_begin_time",NOW_TIME);
	            $session_code = mt_rand(100000, 999999);
	            session('sms_code', $session_code);
	        }
	        D('Api/Sms','Service')->sendSms($phone, $session_code.' 为您的登录验证码（10分钟内有效）');
	        $this->success("发送短信成功！");
        }
      	$this->error("请稍后发送短信验证码。");
    }
}